<template>
  <view class="content user-card">
    <view class="no-auth-box" v-if="!authriotyFlag">
      <img :src="noauthImg" />
      <text>无权限查看</text>
    </view>
    <view v-else class="main-box">
      <view class="example-body">
        <view v-for="item in titleLists" @click="clickItems(item.id)"
          :class="{ 'tag-view': true, active: item.id === curTagIndex }" :key="item.id">
          {{ item.text }}
        </view>
      </view>
      <view class="phxx-list" v-if="curTagIndex === 1">
        <view class="add-btn" @click="createFn(-1)" v-if="authriotyFlagcreate && false">新增</view>
        <view class="seraching-box">
          <view class="uni-flex uni-row">
            <view class="text" style="flex: 1;">
              <uni-notice-bar show-icon scrollable background-color="#ffffff" speed="80" text="数据仅供参考，以调度指挥中心指令为准!" />
            </view>
            <view class="filter-wrap">
              <text :style="{color: isOpenConversion?'#409EFE':'#999999'}"
                @click="openPop('isOpenConversion')">折算</text>
              <uni-icons :color="isOPenColumns?'#409EFE':'#999999'" type="gear-filled" size="22"
                @click="openPop('isOPenColumns')" style="margin-right: 10px;position: relative;top: 2px;"></uni-icons>
              <img @click="openPop('isOpenFilterBox')" class="filter-box"
                :src="isOpenFilterBox?activeFilterIcon:filterIcon" v-if="authriotyFlagfilter" />
            </view>
          </view>
        </view>
        <basic-table ref="customTable" row-key="id" :fit="false" :border="true" :highlight="true" :show-header="true"
          :isShowLoadMore="true" :columns="column" :data="datasLists" :isMore="queryParam.isMore"
          :pullNo="queryParam.pullNo" @edit="createFn" @sort-change="sortChange" @pullUpLoading="pullUpLoading"
          @collectionStatusChange="collectionStatusChange">
        </basic-table>
      </view>
      <view class="tab-item" v-if="curTagIndex === 2">
        <view>
          <image :src="upPlaceIcon" style="width: 200px;height: 110px;" />
          <view>正在建设中，敬请期待...</view>
        </view>
      </view>
      <view class="tab-item" v-if="curTagIndex === 3">
        <view>
          <image :src="upPlaceIcon" style="width: 200px;height: 110px;" />
          <view>正在建设中，敬请期待...</view>
        </view>
      </view>
    </view>
    <custom-columns :show="isOPenColumns" :hiddenSort="hiddenSort" @openChange="openChange"
      @customChange="customChange"></custom-columns>
    <conversion :show="isOpenConversion" @openChange="openChange" @loadTable="conversionChange"></conversion>
    <filterBox :show="isOpenFilterBox" @openChange="openChange" @loadTable="filterBoxChange"></filterBox>
    <uni-popup ref="collectionPopup" border-radius="10px">
      <view class="collection-wrap">
        <view class="title">确认收藏</view>
        <view class="sub-title">{{rowData.collieryName}}-{{rowData.coalName}}</view>
        <view class="input-wrap">
          <text>收藏权重</text>
          <input type="number" v-model="weight" placeholder="请输入" maxlength="9999999" />
        </view>
        <view class="tip">数字越大，排序越靠前！</view>
        <view class="footer-wrap">
          <button type="common" @click="cancelFn">取消</button>
          <button type="primary" @click="submitFn">确认</button>
        </view>
      </view>
    </uni-popup>
    <tip-box :show="showMsgTip" :message="msgTip" :duration="2000" @showTip="event=>showMsgTip=event"></tip-box>
  </view>
</template>
<script>

  import config from '@/config';
  import storage from '@/utils/storage';
  import func from '@/utils/funlogin.js';
  import { toast } from '@/utils/common';
  import { showConfirm } from '@/utils/common';
  import { getAccessToken, setTenantId, removeToken, getNickName } from '@/utils/auth';
  import { getOpenIdByCode, getUserScanQrcode, bindQrCode } from '@/api/login.js';
  import { getMenuAuth, getButtonAuth } from '@/utils/permission';
  import conversion from '@/pages/common/conversion/conversion';
  import filterBox from '@/pages/common/filter-box/filter-box';
  import customColumns from '@/pages/common/custom-columns/custom-columns';
  import { getCollieryList, getCustomColumns, createCoalCollect, deleteCoalCollect, getAllList } from '@/api/colliery.js';

  const key = 'JY2BZ-RJHKW-6GTR3-3PFGV-B5CMS-7WBXV'; //使用在腾讯位置服务申请的key

  export default {
    components: {
      filterBox,
      conversion,
      customColumns
    },
    computed: {
      filterIcon() {
        return config.baseImgUrl + '/mst-filter.png';
      },
      activeFilterIcon() {
        return config.baseImgUrl + '/mst-active-filter.png';
      },
      upPlaceIcon() {
        return config.baseImgUrl + '/up-place.png';
      },
      noauthImg() {
        return config.baseImgUrl + '/no-auth.png';
      }
    },
    data() {
      return {
        rowId: -1,
        curTagIndex: 1,
        column: [],
        datasLists: [],
        locationList: [],
        hiddenSort: [
          'collieryName',
          'coalName',
          'panBreeze',
          'volatileMatter',
          'assayReport',
          'shareholder',
          'positionName',
          'locationName',
          'phone',
          'operation'
        ],
        msgTip: '',
        showMsgTip: false,
        chooseCollieryFlag: false,
        chooseComineFlag: false,
        isOpenConversion: false,
        isOpenFilterBox: false,
        isOPenColumns: false,
        isOPenInput: false,
        authriotyFlag: true,
        authriotyFlagquery: false,
        authriotyFlagfilter: false,
        authriotyFlagsort: false,
        authriotyFlagsalevolume: false,
        authriotyFlagupd: false,
        authriotyFlagcreate: false,
        queryParam: {
          pullNo: 1,
          pageNo: 1,
          pageSize: 20,
          sortMap: {
            name: '',
            sort: ''
          },
          isMore: 'more',
          total: 0
        },
        searchZheData: {
          purchaseCompanyName: undefined,
          railwayFreight: undefined,
          standardCalorificValue: undefined
        },
        searchParam: {
          collieryName: [],
          coalName: [],
          calorificValueStart: undefined,
          calorificValueEnd: undefined,
          sulfurStart: undefined,
          sulfurEnd: undefined
        },
        titleLists: [
          {
            id: 1,
            text: '煤源'
          },
          {
            id: 2,
            text: '站台'
          },
          {
            id: 3,
            text: '用户'
          }
        ],
        rowData: {},
        weight: '1'
      };
    },
    methods: {
      cancelFn() {
        this.weight = '1'
        this.$refs.collectionPopup.close()
      },
      collectionStatusChange(data) {
        this.rowData = data
        if (data.collectionStatus) {
          uni.showModal({
            title: '取消收藏',
            content: `是否取消收藏此煤种【${data.collieryName}-${data.coalName}】？`,
            success: (res) => {
              if (res.confirm) {
                this.deleteCoalCollect()
              }
            }
          });
          return
        }
        this.weight = '1'
        this.$refs.collectionPopup.open()
      },
      submitFn() {
        if (!this.weight) {
          toast('收藏权重不能为空')
          return;
        }
        this.createCoalCollect()
      },
      async createCoalCollect() {
        const res = await createCoalCollect({
          coalBasicId: this.rowData.id,
          collieryId: this.rowData.collieryId,
          collieryName: this.rowData.collieryName,
          coalId: this.rowData.coalId,
          coalName: this.rowData.coalName,
          userName: getNickName(),
          weight: this.weight,
        })
        if (res.code === 0) {
          this.setDataCollectionStatus(true)
          this.cancelFn()
          toast('收藏成功')
        }
      },
      async deleteCoalCollect() {
        const res = await deleteCoalCollect(this.rowData.id)
        if (res.code === 0) {
          this.setDataCollectionStatus(false)
          toast('取消收藏成功')
        }
      },
      setDataCollectionStatus(status) {
        this.datasLists = this.datasLists.map(e => {
          if (e.id === this.rowData.id) {
            e.collectionStatus = status
          }
          return e
        })
      },
      createFn(id) {
        this.isOPenInput = true;
        this.rowId = id;
      },
      openPop(key) {
        this[key] = true;
      },
      openChange(data) {
        this[data.key] = data.show;
      },
      filterBoxChange(data) {
        this.searchParam = JSON.parse(JSON.stringify(data));
        this.initTable();
      },
      conversionChange(data) {
        this.searchZheData = JSON.parse(JSON.stringify(data));
        this.initTable();
      },
      customChange() {
        this.getCustomColumns();
      },
      sortChange(name, sort) {
        this.queryParam.sortMap = {
          name,
          sort
        };
        this.initTable();
      },
      async pullUpLoading() {
        this.queryParam.pageNo++;
        if (this.queryParam.total === this.datasLists.length) {
          this.queryParam.isMore = 'noMore';
          return;
        }
        await this.getRowList();
        this.queryParam.pullNo++;
      },
      clickItems(id) {
        this.curTagIndex = id;
        if (id === 1) {
          this.initTable();
        }
      },
      async bindWxInfo(userId) {
        const code = await func.wxLogin();
        const openObj = await getOpenIdByCode(code);
        const openId = openObj?.data
        const res = await getUserScanQrcode({ userId, openId })
        if (res.code === 0) {
          this.handleWxInfo(res.data, userId, openId)
        } else {
          toast(res.msg)
        }
        uni.hideLoading();
      },
      handleWxInfo(result, userId, openId) {
        switch (result.resultStatus) {
          case 1:
            this.msgTip = result.resultMessage
            this.showMsgTip = true
            // toast(result.resultMessage)
            break;
          case 2:
            uni.reLaunch({
              url: `/packageA/pages/pwSet/index?userId=${userId}&openId=${openId}`
            });
            break;
          case 3:
            showConfirm(result.resultMessage).then((res) => {
              if (res.confirm) {
                this.bindQrCode({ id: userId, openId })
              }
            });
            break;
          case 4:
            uni.reLaunch({
              url: '/packageA/pages/login'
            });
            break;
          default: break
        }
      },
      async bindQrCode(data) {
        const res = await bindQrCode(data)
        if (res.code === 0 && res.data) {
          uni.reLaunch({
            url: '/packageA/pages/login'
          });
          toast('用户绑定成功,请重新登录')
        }
      },
      // 获取登录状态
      async getLoginStatus() {
        console.log('getAccessToken()', getAccessToken())
        if (getAccessToken()) {
          this.getMenuAuth();
          return
        }
        uni.hideLoading();
        showConfirm('检测到当前未登录，是否登录?').then((res) => {
          if (res.confirm) {
            removeToken();
            storage.clean();
            uni.reLaunch({
              url: '/packageA/pages/login'
            });
          }
        });
      },
      async getMenuAuth() {
        const auth = await getMenuAuth('datas');
        this.$nextTick(() => {
          if (auth) {
            this.authriotyFlag = true;
            this.getButtonAuth();
          } else {
            this.authriotyFlag = false;
          }
        });
      },
      async getButtonAuth() {
        const authMarksMap = {
          'govern:colliery:query': 'authriotyFlagquery',
          'govern:colliery:filter': 'authriotyFlagfilter',
          'govern:colliery:sort': 'authriotyFlagsort',
          'govern:colliery:salevolume': 'authriotyFlagsalevolume',
          'govern:colliery:update': 'authriotyFlagupd',
          'govern:colliery:create': 'authriotyFlagcreate'
        };
        const buttonAuths = await getButtonAuth(Object.keys(authMarksMap));
        buttonAuths.forEach(async (key) => {
          if (key === 'govern:colliery:query') {
            await this.getAllListFn()
            this.searchZheData.purchaseCompanyName = this.locationList.find(e => e.purchaseCompanyId === 87)?.purchaseCompanyName
            await this.getCustomColumns();
            this.initTable();
          }
          this[authMarksMap[key]] = true;
        });
      },
      async getAllListFn() {
        const res = await getAllList();
        if (res.code === 0) {
          this.locationList = res?.data || [];
        } else {
          toast(res.msg);
        }
      },
      async getCustomColumns() {
        const res = await getCustomColumns({
          menuType: 'coalBasicData'
        });
        if (res.code === 0) {
          const result = res.data?.fieldAttributeList || [];
          this.column = [{
            emptyString: "--",
            fixed: true,
            hidden: false,
            label: "收藏",
            name: "",
            renders: null,
            sorter: null,
            type: 'icon',
            width: 60
          }, ...result]
        }
      },
      initTable() {
        this.queryParam.pageNo = 1;
        this.datasLists = [];
        this.getRowList();
      },
      getFilterParams() {
        const data = {};
        if (this.searchParam.collieryName.length) {
          data['collieryNames'] = this.searchParam.collieryName || [];
        }
        if (this.searchParam.coalName.length) {
          data['coalNames'] = this.searchParam.coalName || [];
        }
        if (this.searchParam.calorificValueStart) {
          data['calorificValueStart'] = this.searchParam.calorificValueStart;
        }
        if (this.searchParam.calorificValueEnd) {
          data['calorificValueEnd'] = this.searchParam.calorificValueEnd;
        }
        if (this.searchParam.sulfurStart) {
          data['sulfurStart'] = this.searchParam.sulfurStart;
        }
        if (this.searchParam.sulfurEnd) {
          data['sulfurEnd'] = this.searchParam.sulfurEnd;
        }
        if (this.searchZheData.purchaseCompanyName) {
          data['purchaseCompanyName'] = this.searchZheData.purchaseCompanyName;
        }
        if (this.searchZheData.railwayFreight) {
          data['railwayFreight'] = this.searchZheData.railwayFreight;
        }
        if (this.searchZheData.standardCalorificValue) {
          data['standardCalorificValue'] =
            this.searchZheData.standardCalorificValue;
        }
        if (this.queryParam.sortMap.name) {
          data[`${this.queryParam.sortMap.name}Sorter`] =
            this.queryParam.sortMap.sort;
        }
        return data;
      },
      async getRowList() {
        const data = {
          showSales: true,
          pageNo: this.queryParam.pageNo,
          pageSize: this.queryParam.pageSize
        };
        const params = { ...data, ...this.getFilterParams() };
        let res = await getCollieryList(params);
        if (res.code == 0) {
          this.queryParam.total = res.data.total;
          const result = res.data.list || [];
          this.datasLists = [
            ...this.datasLists,
            ...this.handleDataList([...result])
          ];
        } else {
          toast(res.msg);
        }
        uni.hideLoading();
        //停止下拉刷新
        wx.hideNavigationBarLoading();
        //停止下拉刷新
        wx.stopPullDownRefresh();
      },
      handleDataList(list) {
        return list.map((e) => {
          e.salesDay = this.authriotyFlagsalevolume ? e.salesDay : '';
          e.salesWeek = this.authriotyFlagsalevolume ? e.salesWeek : '';
          e.salesMonth = this.authriotyFlagsalevolume ? e.salesMonth : '';
          return e;
        });
      },
      handleQuery(query) {
        const obj = {}
        const paramsStr = query?.split('{')?.[1]?.split('}')?.[0]
        const queryList = paramsStr?.split(',') || []
        queryList.forEach(value => {
          const valueList = value.split(':')
          obj[valueList[0]] = valueList[1]
        })
        return obj
      }
    },
    onLoad(option) {
      uni.showLoading({
        title: '数据加载中...'
      });
      if (option.q) {
        const query = decodeURIComponent(option.q)
        const { tenantId, userId } = this.handleQuery(query)
        removeToken();
        storage.clean();
        setTenantId(tenantId)
        this.bindWxInfo(userId)
      } else {
        this.getLoginStatus();
      }
    },
    onPullDownRefresh() {
      this.initTable()
    }
  };
</script>

<style lang="scss" scoped>
  .content {
    position: relative;
    width: 100%;
    height: 100vh;

    .add-btn {
      width: 40px;
      height: 40px;
      position: fixed;
      bottom: 10px;
      z-index: 99;
      background: #3fa5d6;
      border-radius: 50%;
      color: #fff;
      text-align: center;
      line-height: 40px;
      left: 10px;
      cursor: pointer;
    }

    .phxx-list {
      padding: 2px;
      width: 100%;
      height: calc(100vh - 50px);
      overflow: hidden;

      .seraching-box {
        text-align: right;
        height: 40px;
        line-height: 40px;
      }
    }
  }

  .filter-wrap {
    display: flex;
    align-items: center;
    background-color: #ffffff;

    text {
      font-size: 14px;
      color: #999999;
      margin-right: 10px;
    }

    .filter-box {
      width: 20px;
      height: 20px;
      margin-right: 10px;
    }
  }

  .tab-item {
    display: flex;
    justify-content: center;
    margin-top: 35%;

    >view {
      display: flex;
      flex-direction: column;
      align-items: center;

      >view {
        margin-top: 20px;
      }
    }
  }

  .collection-wrap {
    width: 300px;
    padding: 15px;
    border-radius: 10px;
    background-color: #fff;

    .title {
      font-size: 16px;
      font-weight: bold;
      text-align: center;
    }

    .sub-title {
      margin-top: 10px;
    }

    .input-wrap {
      margin-top: 10px;
      display: flex;
      align-items: center;

      text {
        margin-right: 10px;
      }

      input {
        flex: 1;
        height: 28px;
        padding: 0 4px;
        border-radius: 4px;
        border: 1px solid #c7cede;
      }
    }

    .tip {
      margin: 10px 0 0 58px;
    }

    .footer-wrap {
      margin-top: 20px;
      display: flex;
      align-items: center;
      justify-content: space-around;

      button {
        color: #fff;
        border-radius: 4px;
        border: 0 !important;
        margin: 0 !important;
        height: 28px !important;
        font-size: 14px !important;
        line-height: 28px !important;
      }

      button[type="common"] {
        border: 0 !important;
        color: #666666 !important;
        background-color: #eeeff2 !important;
      }
    }
  }
</style>